﻿using Microsoft.AspNetCore.Http;
using Microsoft.IdentityModel.Tokens;
using MyFramework.Plugins.Core.Configuration;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace MyFramework.Plugins.Core.Core
{
    /// <summary>
    /// 
    /// </summary>
    public class MyJwtHelper
    {
        /// <summary>
        /// 生成Token
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        public static string GetToken(string code, string pwd)
        {
            //秘钥
            var securityKey = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(AppSettings.JwtSetting.SecurityKey)), SecurityAlgorithms.HmacSha256);

            //Claim
            var claims = new Claim[] {
                   //new Claim(JwtRegisteredClaimNames.Sid,""),
                   new Claim(JwtRegisteredClaimNames.Iss,AppSettings.JwtSetting.Issuer),
                   new Claim(JwtRegisteredClaimNames.Sub,code),
                   new Claim("Guid",Guid.NewGuid().ToString("D")),
           };

            SecurityToken securityToken = new JwtSecurityToken(
                           issuer: AppSettings.JwtSetting.Issuer,
                           audience: AppSettings.JwtSetting.Audience,
                           signingCredentials: securityKey,
                           expires: DateTime.Now.AddMinutes(2),//过期时间
                           claims: claims
                           );
            return new JwtSecurityTokenHandler().WriteToken(securityToken);
        }

        /// <summary>
        /// 获取accessToken
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public static string GetTokenString(HttpContext context)
        {
            return context != null ? context.Request.Headers["Authorization"].ToString() : "";
        }

        /// <summary>
        /// 解析Jwt生成的 Tocken
        /// </summary>
        /// <param name="accesTocken"></param>
        /// <returns></returns>
        public static NameValueCollection GetTokenInfo(string accesTocken)
        {
            try
            {
                if (accesTocken.Contains("Bearer")) //防止前端传过来的tocken 为待了 Bearer 的字符串
                {
                    accesTocken = accesTocken.Replace("Bearer ", "");
                }
                var tockHandler = new JwtSecurityToken(accesTocken);
                NameValueCollection nameValueCollection = new NameValueCollection();
                //nameValueCollection.Add(JwtRegisteredClaimNames.Sid, tockHandler.Claims.FirstOrDefault(c => c.Type == JwtRegisteredClaimNames.Sid).Value);
                nameValueCollection.Add(JwtRegisteredClaimNames.Sub, tockHandler.Claims.FirstOrDefault(c => c.Type == JwtRegisteredClaimNames.Sub).Value);
                nameValueCollection.Add("Guid", tockHandler.Claims.FirstOrDefault(c => c.Type == "Guid").Value);
                nameValueCollection.Add(JwtRegisteredClaimNames.Iss, tockHandler.Claims.FirstOrDefault(c => c.Type == JwtRegisteredClaimNames.Iss).Value);
                return nameValueCollection;
            }
            catch (Exception ex)
            {
                throw new Exception("解析Token时错误！");
            }
        }
    }
}